use super::category::get_all_apps;
use crate::utils::format::format_icon_url;
use crate::{
    handlers::server::get_json_server_url,
    models::app::{AppDetail, AppItem},
    utils::UA,
};

#[tauri::command]
pub async fn get_app_info(category: String, pkgname: String) -> Result<AppDetail, String> {
    use crate::models::app::AppDetail;
    use crate::utils::UA;

    // 获取服务器URL
    let json_server_url = get_json_server_url();
    let url = format!("{}{}/{}/app.json", json_server_url, category, pkgname);

    // 创建HTTP客户端并发送请求
    let response = reqwest::Client::new()
        .get(&url)
        .header("User-Agent", UA)
        .send()
        .await
        .map_err(|e| format!("获取应用信息失败: {}", e))?
        .text()
        .await
        .map_err(|e| format!("读取响应内容失败: {}", e))?;

    // 直接解析JSON响应为AppDetail结构体
    let mut app_info: AppDetail =
        serde_json::from_str(&response).map_err(|e| format!("解析应用信息JSON失败: {}", e))?;

    // 设置图标URL和下载次数
    app_info.category = Some(category.clone());
    app_info.icon = Some(format_icon_url(&category.clone(), &app_info.pkgname));
    app_info.download_times = Some(
        get_download_times(category, pkgname)
            .await
            .map_err(|e| format!("获取下载次数失败: {}", e))?,
    );

    Ok(app_info)
}

pub async fn get_download_times(category: String, pkgname: String) -> Result<i32, String> {
    let json_server_url = get_json_server_url();
    let url = format!(
        "{}{}/{}/download-times.txt",
        json_server_url, category, pkgname
    );

    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .header("User-Agent", UA)
        .send()
        .await
        .map_err(|e| e.to_string())?;

    let times = response
        .text()
        .await
        .map_err(|e| e.to_string())?
        .trim()
        .parse::<i32>()
        .map_err(|e| e.to_string())?;

    Ok(times)
}

#[tauri::command]
pub async fn search_all_apps(query: String) -> Result<Vec<AppItem>, String> {
    let all_apps = get_all_apps().await?;
    Ok(crate::utils::search::search_apps(&all_apps, &query))
}
